#import "Core.h"

@interface EditPurposeViewController (private)

- (void)onSave;
- (void)showProgress;
- (void)hideProgress;
- (void)saveHistory;
- (void)loadHistory;

@end

@implementation EditPurposeViewController (private)

- (void)onSave 
{
	// 먼저 히스토리를 저장해주고 델리게이트 콜백을 호출한다.
	[_purposeDataList addPurpose:_purposeView.text];
	[self saveHistory];
	
	// 기도화면에서 콜백을 받았을 경우 지향만 바꿔주고, 히스토리에서 콜백을 받을 경우 데이터를 다시 읽는다.
	[_delegate onSavePurpose:_purposeView.text];
	
	// pop current view
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)showProgress
{
	[self.view addSubview:_progress];
	[_progress startAnimating];	
}

- (void)hideProgress
{
	[_progress stopAnimating];
	[_progress removeFromSuperview];
}

- (void)saveHistory
{
	if( _purposeDataList == nil )
		return;
	
	if( [_purposeDataList getNumberOfData] == 0 )
		return;

	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	[NSKeyedArchiver archiveRootObject:_purposeDataList toFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, _filename]];
}

- (void)loadHistory
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];

	if( NO == [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, _filename]] )
	{
		_purposeDataList = [[PurposeDataList alloc] init];
		[_purposeView becomeFirstResponder];
		[self hideProgress];
		return;
	}
	
	_purposeDataList = (PurposeDataList*)[[NSKeyedUnarchiver unarchiveObjectWithFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, _filename]] retain];
	[_purposeView becomeFirstResponder];
	[self hideProgress];
}

@end

@implementation EditPurposeViewController

@synthesize delegate = _delegate;

- (id)initWithPurpose:(NSString*)purpose rootViewController:(PrayViewController*)rootViewController filename:(NSString *)filename
{
	if( (self = [super initWithRootViewController:rootViewController]) != nil )
	{
		_purpose = purpose;
		_filename = filename;
	}
	
	return self;
}

- (void)viewDidLoad
{
	CGRect rect;
	
	self.view.frame = CGRectMake(0, 0, 320, 390);
	self.view.backgroundColor = [UIColor blackColor];
	self.title = @"지향 수정";
	
	_purposeView = [[UITextView alloc] initWithFrame:CGRectMake(0, 10, 320, 200)];
	_purposeView.text = _purpose;
	_purposeView.font = [UIFont systemFontOfSize:20.0f];
	_purposeView.keyboardType = UIKeyboardTypeASCIICapable;
	

	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave 
																						  target:self 
																						   action:@selector(onSave)];
	
	_progress = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	
	rect = _progress.frame;
	rect.origin.x = 160 - rect.size.width / 2;
	rect.origin.y = 160 - rect.size.height / 2;
	_progress.frame = rect;
	
	[self showProgress];
	[self loadHistory];
	
	[self.view addSubview:_purposeView];
}

@end

@interface PurposeHistoryViewController (private)

- (void)onAdd;
- (void)onEdit;
- (void)onDone;
- (void)showProgress;
- (void)hideProgress;
- (void)saveHistory;
- (void)loadHistory;

@end

@implementation PurposeHistoryViewController (private)

- (void)onAdd
{
	EditPurposeViewController*	purposeC = [[EditPurposeViewController alloc] initWithPurpose:@""
																		  rootViewController:_rootViewController  
																					filename:_filename];
	purposeC.delegate = self;
	[self.navigationController pushViewController:purposeC animated:YES];
	[purposeC release];
}

- (void)onEdit
{
	[self.tableView setEditing:YES animated:YES];
	
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
																						   target:self 
																						action:@selector(onDone)];
}

- (void)onDone
{
	[self.tableView setEditing:NO animated:YES];
	
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit 
																						   target:self 
																						   action:@selector(onEdit)];
}

- (void)showProgress
{
	[self.view addSubview:_progress];
	[_progress startAnimating];	
}

- (void)hideProgress
{
	[_progress stopAnimating];
	[_progress removeFromSuperview];
}

- (void)saveHistory
{
	if( _purposeDataList == nil )
		return;
	
	if( [_purposeDataList getNumberOfData] == 0 )
		return;
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	[NSKeyedArchiver archiveRootObject:_purposeDataList toFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, _filename]];
}

- (void)loadHistory
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];

	if( NO == [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, _filename]] )
	{
		_purposeDataList = [[PurposeDataList alloc] init];
		[self hideProgress];
		return;
	}
	
	_purposeDataList = [(PurposeDataList*)[NSKeyedUnarchiver unarchiveObjectWithFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, _filename]] retain];
	_numberOfRow = [_purposeDataList getNumberOfData];
	
	[self hideProgress];
	[self.tableView reloadData];
}

@end

@implementation PurposeHistoryViewController

@synthesize delegate = _delegate;

- (id)initWithRootViewController:(PrayViewController *)rootViewController withStyle:(UITableViewStyle)style andFileName:(NSString*)filename
{
	self = [super initWithRootViewController:rootViewController withStyle:style];
	
	if( self != nil )
	{
		_filename = filename;
	}

	return self;
}

- (void)viewDidLoad
{
	CGRect rect;
	
	[super viewDidLoad];

	self.title = @"지향 히스토리";
	
	_progress = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	
	rect = _progress.frame;
	rect.origin.x = 160 - rect.size.width / 2;
	rect.origin.y = 160 - rect.size.height / 2;
	_progress.frame = rect;
	
//	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit 
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
																						   target:self 
																						   action:@selector(onAdd)];
	
	[self showProgress];
	[self loadHistory];
	
	_numberOfRow = 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return _numberOfRow;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell*	cell;
	PurposeData*		purposeData;
	
	cell = [tableView dequeueReusableCellWithIdentifier:@"default"];
	
	if( cell == nil )
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"default"] autorelease];
	}

	purposeData = [_purposeDataList getPurposeWithIndex:indexPath.row];
	cell.textLabel.text = purposeData.purpose;
	//cell.detailTextLabel.text = [purposeData.date description];
	
	return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 40.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	EditPurposeViewController*	purposeC = [[EditPurposeViewController alloc] initWithPurpose:[_purposeDataList getPurposeWithIndex:indexPath.row].purpose 
																		  rootViewController:_rootViewController  
																					filename:_filename];
	purposeC.delegate = self;
	[self.navigationController pushViewController:purposeC animated:YES];
	[purposeC release];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
	[_purposeDataList deletePurposeAtIndex:indexPath.row];
	_numberOfRow = [_purposeDataList getNumberOfData];
	[self saveHistory];
	
	[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
	
	if( _numberOfRow == 0 )
	{
		[self onSavePurpose:@""];
	}
	else
	{
		[self onSavePurpose:[_purposeDataList getPurposeWithIndex:_numberOfRow-1].purpose];
	}
}

- (void)onSavePurpose:(NSString*)newPurpose
{
	[self loadHistory];
	[self.tableView reloadData];
	
	if( _delegate != nil )
		[_delegate onSavePurpose:newPurpose];
}

@end
